package net.dianpin.controller;

import net.dianpin.dao.generate.UserMapper;
import net.dianpin.model.generate.User;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class HelloWorldController implements BeanFactoryAware{

    private SqlSessionFactory sqlSessionFactory;
    private UserMapper userMapper;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        sqlSessionFactory = beanFactory.getBean("sqlSessionFactory",SqlSessionFactory.class);
        userMapper = sqlSessionFactory.openSession().getMapper(UserMapper.class);
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(
            @RequestParam(defaultValue = "店聘",required = true,value = "name") String name,
            @ModelAttribute("model") ModelMap model,
            HttpServletResponse response) {
        List<User> myUserList = userMapper.selectByExample(null);
        model.addAttribute("message", myUserList.get(0).getUserName());
        model.addAttribute("userList", myUserList);
        response.setContentType("text/html;charset=UTF-8");

        return "helloworld";
    }


    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(
            @RequestParam(defaultValue = "店聘",required = true,value = "name") String name,
            @ModelAttribute("model") ModelMap model,
            HttpServletResponse response) {
        List<User> myUserList = userMapper.selectByExample(null);
        model.addAttribute("message", myUserList.get(0).getUserName());
        model.addAttribute("userList", myUserList);
        response.setContentType("text/html;charset=UTF-8");
        return "index";
    }


}
